// 后期添加账号详情
import React, { Component } from 'react';
import {
  Card,
  Form,
  Table,
  Button,
  Input,
  Modal,
  Radio,
  Select,
  DatePicker,
  TimePicker,
  Badge,
  Tag,
  Popconfirm,
  message,
} from 'antd';
import {
  createAccount,
  queryAccount,
  deleteAccount,
  updateAccount,
  queryAccountType,
} from '@/services/account';
import { connect } from 'dva';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import moment from 'moment';
import './index.less';
// 获取model
const { MonthPicker, RangePicker } = DatePicker;
@connect(({ account }) => ({
  accountList: account.accountList,
}))
@Form.create()
class AccountList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      accountList: [],
      isAccountFormVisible: false,
      status: 1,
      type: '',
      tableLoading: false,
      // 判断初始操作状态
      currentOption: 'create',
      currentId: '',
      // 类型
      typeData: [],
    };
  }
  componentDidMount() {
    this.initialAccount();
    this.initialType();
  }
  // 初始获取类型

  initialType = async () => {
    const res = await queryAccountType();
    this.setState({
      typeData: res.data.list,
      type: res.data.list[0].value,
    });
  };
  // 获取账户列表
  initialAccount = async () => {
    this.setState({
      tableLoading: true,
    });
    // const { dispatch, accountList } = this.props;
    // // 调用redux，获取数据
    // dispatch({
    //   type: 'account/fetchAccount',
    // });
    // console.log(accountList);
    // console.log('---->accountList');

    // 全局赋值

    // 全局赋值
    const res = await queryAccount();
    console.log(res.data.list);
    setTimeout(() => {
      this.setState(
        {
          accountList: res.data.list,
        },
        () => {
          this.setState({
            tableLoading: false,
          });
        },
      );
    }, 1500);
  };
  // 添加账号弹窗
  handleAddAccount = () => {
    this.setState({
      isAccountFormVisible: true,
      currentOption: 'create',
    });
  };
  // 提交数据
  handleAccountSubmit = e => {
    e.preventDefault();
    console.log('12');
    const _this = this;
    this.props.form.validateFields((err, fieldsValue) => {
      if (!err) {
        console.log(fieldsValue);
        // 处理时间
        const values = {
          ...fieldsValue,
          dueTime: fieldsValue['dueTime'].format('YYYY-MM-DD'),
        };
        console.log(values);
        this.submitForm(values);

        this.props.form.resetFields();
        this.initialAccount();
      }
    });
  };
  submitForm = async value => {
    // 判断是编辑还是新增

    const { currentOption } = this.state;
    if (currentOption == 'create') {
      const res = await createAccount(value);
      if (res.code == 0) {
        message.success('添加成功');
      }
      setTimeout(() => {
        this.setState({
          isAccountFormVisible: false,
        });
      }, 1000);
    } else {
      const _id = this.state.currentId;
      const values = { ...value, _id };

      const res = await updateAccount(values);
      if (res.code == 0) {
        message.success('修改成功');
      }
      this.initialAccount();
      setTimeout(() => {
        this.setState({
          isAccountFormVisible: false,
        });
      }, 1000);
    }
  };
  // 关闭弹窗
  handleCancel = e => {
    console.log(e);
    this.setState({
      isAccountFormVisible: false,
    });
    this.props.form.resetFields();
  };
  // 删除气泡
  handleDelete = async record => {
    console.log(record._id);
    const id = record._id;
    const res = await deleteAccount({ id });
    if (res.code == 0) {
      message.success('删除成功');
      this.initialAccount();
    }
  };
  // 编辑
  handleEditAccount = record => {
    console.log(record.dueTime);
    this.props.form.setFieldsValue(
      {
        dueTime: moment(record.dueTime, 'YYYY/MM/DD'),
        password: record.password,
        status: record.status,
        title: record.title,
        type: record.type,
      },
      () => {
        console.log('赋值');
        this.setState({
          isAccountFormVisible: true,
          currentOption: 'update',
          currentId: record._id,
        });
      },
    );
  };
  handleDeleteCancel = () => {};
  handleAsync = () => {
    this.initialAccount();
  };
  render() {
    const { accountList, isAccountFormVisible, status, type, tableLoading, typeData } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    const columns = [
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
      },
      {
        title: '账号',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '密码',
        dataIndex: 'password',
        key: 'password',
      },

      {
        title: '状态',
        key: 'status',
        render: record => {
          return (
            <div>
              {record.status == '1' && <Tag color="#52c41a">使用中</Tag>}
              {record.status == '2' && <Tag color="#1890ff">空闲</Tag>}
            </div>
          );
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
      },
      {
        title: '到期时间',
        dataIndex: 'dueTime',
        key: 'dueTime',
      },
      {
        title: '操作',
        key: 'action',
        align: 'center',
        render: record => {
          return (
            <div>
              <Button type="link" onClick={() => this.handleEditAccount(record)}>
                编辑
              </Button>
              <Popconfirm
                title="确定删除?"
                onConfirm={() => this.handleDelete(record)}
                onCancel={this.handleDeleteCancel}
                okText="是"
                cancelText="否"
              >
                <Button type="link">删除</Button>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    return (
      <PageHeaderWrapper>
        <div>
          <Card title="账号列表">
            {' '}
            <div>
              <div style={{ marginBottom: '20px' }}>
                <Button type="primary" onClick={this.handleAddAccount}>
                  添加
                </Button>
                <Button onClick={this.handleAsync} style={{ float: 'right' }}>
                  刷新
                </Button>
              </div>
              <Table loading={tableLoading} columns={columns} dataSource={accountList}></Table>
            </div>
            <Modal
              visible={isAccountFormVisible}
              onOk={this.handleAccountSubmit}
              onCancel={this.handleCancel}
            >
              <Form {...formItemLayout} labelAlign="left">
                <Form.Item label="账号" style={{ marginTop: '20px' }}>
                  {getFieldDecorator('title', {
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Input placeholder="填写账号"></Input>)}
                </Form.Item>
              </Form>
              <Form {...formItemLayout} labelAlign="left">
                <Form.Item label="密码">
                  {getFieldDecorator('password', {
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Input placeholder="填写密码"></Input>)}
                </Form.Item>
                <Form.Item label="账号类型">
                  {getFieldDecorator('type', {
                    rules: [
                      {
                        required: true,
                      },
                    ],
                    initialValue: type,
                  })(
                    <Select>
                      {typeData.map(v => {
                        return <Select.Option value={v.name}>{v.name}</Select.Option>;
                      })}
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item label="账号状态">
                  {getFieldDecorator('status', {
                    rules: [
                      {
                        required: true,
                      },
                    ],
                    initialValue: status,
                  })(
                    <Radio.Group>
                      <Radio value="1">使用中</Radio>
                      <Radio value="2">已停用</Radio>
                    </Radio.Group>,
                  )}
                </Form.Item>
                <Form.Item label="到期时间">
                  {getFieldDecorator('dueTime', {})(<DatePicker />)}
                </Form.Item>
              </Form>
            </Modal>
          </Card>
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default AccountList;
